{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b53717ac",
   "metadata": {},
   "source": [
    "| [02_advanced/05_上下文管理器.ipynb](https://github.com/shibing624/python-tutorial/blob/master/02_advanced/05_上下文管理器.ipynb)  | with语句  |[Open In Colab](https://colab.research.google.com/github/shibing624/python-tutorial/blob/master/02_advanced/05_上下文管理器.ipynb) |\n",
    "\n",
    "# 上下文管理器\n",
    "\n",
    "## with\n",
    "生成文件："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b6614a0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('my_file.txt', 'w') as fp:\n",
    "    data = fp.write(\"Hello world\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa3ece5f",
   "metadata": {},
   "source": [
    "这等效于下面的代码，但是要更简便："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "fbde4e89",
   "metadata": {},
   "outputs": [],
   "source": [
    "fp = open('my_file.txt', 'w')\n",
    "try:\n",
    "    # do stuff with f\n",
    "    data = fp.write(\"Hello world\")\n",
    "finally:\n",
    "    fp.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "07a43c0a",
   "metadata": {},
   "source": [
    "## 自定义上下文管理器\n",
    "比如可以这样定义一个简单的上下文管理器："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "035dc02d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Entering\n",
      "inside operate\n",
      "Exiting\n"
     ]
    }
   ],
   "source": [
    "class ContextManager(object):\n",
    "    def __enter__(self):\n",
    "        print(\"Entering\")\n",
    "\n",
    "    def __exit__(self, exc_type, exc_value, traceback):\n",
    "        print(\"Exiting\")\n",
    "\n",
    "\n",
    "with ContextManager():\n",
    "    print(\"inside operate\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "777f607f",
   "metadata": {},
   "source": [
    "### __enter__ 的返回值\n",
    "如果在 __enter__ 方法下添加了返回值，\n",
    "\n",
    "那么我们可以使用 as 把这个返回值传给某个参数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f2a62be2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Entering\n",
      "my value\n",
      "Exiting\n"
     ]
    }
   ],
   "source": [
    "class ContextManager2(object):\n",
    "    def __enter__(self):\n",
    "        print(\"Entering\")\n",
    "        return \"my value\"\n",
    "\n",
    "    def __exit__(self, exc_type, exc_value, traceback):\n",
    "        print(\"Exiting\")\n",
    "\n",
    "\n",
    "with ContextManager2() as val:\n",
    "    print(val)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f18e00d9",
   "metadata": {},
   "source": [
    "一个通常的做法是将 __enter__ 的返回值设为这个上下文管理器对象本身，\n",
    "文件对象就是这样做的."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "0f48cd7a",
   "metadata": {},
   "outputs": [],
   "source": [
    "class ContextManager3(object):\n",
    "    def __enter__(self):\n",
    "        print(\"Entering\")\n",
    "        return self\n",
    "\n",
    "    def __exit__(self, exc_type, exc_value, traceback):\n",
    "        print(\"Exiting\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e1932df",
   "metadata": {},
   "source": [
    "### 错误处理\n",
    "上下文管理器对象将错误处理交给 __exit__ 进行，可以将错误类型，\n",
    "错误值和 traceback 等内容作为参数传递给 __exit__ 函数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "5c269f22",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Entering\n",
      "Exiting\n",
      "  Exception: division by zero\n"
     ]
    }
   ],
   "source": [
    "class ContextManager4(object):\n",
    "    def __enter__(self):\n",
    "        print(\"Entering\")\n",
    "\n",
    "    def __exit__(self, exc_type, exc_value, traceback):\n",
    "        print(\"Exiting\")\n",
    "        if exc_type is not None:\n",
    "            print(\"  Exception:\", exc_value)\n",
    "            return True  # 不想让错误抛出，只需要将 __exit__ 的返回值设为 True\n",
    "\n",
    "\n",
    "with ContextManager4():\n",
    "    print(1 / 0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "d0aa823f",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.remove('my_file.txt')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fc04883c",
   "metadata": {},
   "source": [
    "本节完。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}